package com.amanda.reggie.service.impl;

import com.amanda.reggie.common.CustomException;
import com.amanda.reggie.entity.Category;
import com.amanda.reggie.entity.Dish;
import com.amanda.reggie.entity.Setmeal;
import com.amanda.reggie.mapper.CategoryMapper;
import com.amanda.reggie.service.CategoryService;
import com.amanda.reggie.service.DishService;
import com.amanda.reggie.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author amanda
 * @Description 分类业务实现
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 根据id删除分类，删除之前对关联的表进行判断
     */
    @Override
    public void remove(Long id) {
        // 1、查询当前分类是否关联了菜品
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        // 1.1 添加查询条件
        dishQueryWrapper.eq(null != id, Dish::getCategoryId, id);
        int dishCount = dishService.count(dishQueryWrapper);
        if (dishCount > 0) {
            // 1.2 如果已经关联则抛出业务异常
            throw new CustomException("当前分类项关联了菜品，不能删除！");
        }
        // 2、查询当前分类是否关联了套餐
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        // 2.1 添加查询条件
        setmealQueryWrapper.eq(null != id, Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealQueryWrapper);
        if (setmealCount > 0) {
            // 2.2 如果已经关联则抛出业务异常
            throw new CustomException("当前分类项关联了套餐，不能删除！");
        }
        // 3、正常删除
        super.removeById(id);
    }

    /**
     * 分类信息分页查询
     */
    @Override
    public Page<Category> pageQuery(int page, int pageSize) {
        // 1、构造分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        // 2、构造条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 3、排序
        lambdaQueryWrapper.orderByDesc(Category::getSort);
        return categoryService.page(pageInfo, lambdaQueryWrapper);
    }

    /**
     * 分类项的回显
     */
    @Override
    public List<Category> getList(Category category) {
        // 1、构建条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        // 2、添加条件
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        // 3、排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        return categoryService.list(queryWrapper);
    }
}
